﻿using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Tensop.Net.Tcp
{
    internal class MemoryAlloc
    {
        private int                     m_count;
        private int                     m_size;
        private Stack<byte[]>           m_pool;

        public MemoryAlloc(int size, int count)
        {
            m_size = size;
            m_count = count * 3;
            m_pool = new Stack<byte[]>( m_count );

            for (int i = 0; i < m_count; i++)
            {
                m_pool.Push( new byte[ m_size ] );
            }
        }

        public ArraySegment<byte> Copy(SocketAsyncEventArgs e)
        {
            byte[] seg;
            lock (m_pool)
            {
                seg = m_pool.Pop();
            }
            Buffer.BlockCopy( e.Buffer, e.Offset, seg, 0, e.BytesTransferred );
            return new ArraySegment<byte>( seg, 0, e.BytesTransferred );
        }

        public void Push(ArraySegment<byte> src)
        {
            if (src.Array.Length != m_size)
                throw new Exception( "" );
            lock (m_pool)
            {
                m_pool.Push( src.Array );
            }
        }
    }
}
